//
// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-11-30  Jed Young  Creation
//

using isql
using chunmapData
using chunmapModel
using slanData
using slanOrm

class DataReader
{
  SqlConn conn
  Schema? schema { private set }

  //field name
  const Str geometry := "geometry"
  const Str skey := "skey"
  const Str[] other := [,]
  const Str table := "Road"
  const Str id := "id"

  new make(|This| f)
  {
    f(this)
  }

  virtual DataUnit find(Str key)
  {
    dataUnit := DataUnit(key)
    otherStr := "," + other.join(",")
    conn.query("select $id, $geometry $otherStr from $table where $skey = '$key'") |set|
    {
      if (schema == null)
      {
        schema = SqlUtil.colsToSchema("$table", set.cols)
      }

      values := [,]
      other.each |v, i| { values.add(set.get(i+2)) }
      shape := ShapeFeature(schema, values)
      {
        it.id = set.get(0)
        it.geometry = getGeometry(set.get(1))
      }
      dataUnit.features.add(shape)
    }
    return dataUnit
  }

  virtual Geometry getGeometry(Buf buf)
  {
    Geometry.fromStream(buf.in)
  }
}